<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="/blog/lib/pace/pace-theme-bounce.min.css">
  <script src="/blog/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"ipvb.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false,"b2t":true,"scrollpercent":true},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="1. Java NIO BufferBuffer是一个抽象类，位于java.nio包中，主要用作缓冲区。Buffer缓冲区本质上是一块可以写入数据，然后可以从中读取数据的内存。这块内存被包装成NIO Buffer对象，并提供了一组方法，用来方便的访问该块内存。 注意：Buffer是非线程安全类。 1.1. Buffer类型的标记属性Buffer在内部也是利用byte[]作为内存缓冲区，只不过多提供">
<meta property="og:type" content="article">
<meta property="og:title" content="Java NIO Buffer">
<meta property="og:url" content="https://ipvb.gitee.io/blog/2020/05/22/Java%20NIO%20Buffer/index.html">
<meta property="og:site_name" content="Chenyumeng的博客">
<meta property="og:description" content="1. Java NIO BufferBuffer是一个抽象类，位于java.nio包中，主要用作缓冲区。Buffer缓冲区本质上是一块可以写入数据，然后可以从中读取数据的内存。这块内存被包装成NIO Buffer对象，并提供了一组方法，用来方便的访问该块内存。 注意：Buffer是非线程安全类。 1.1. Buffer类型的标记属性Buffer在内部也是利用byte[]作为内存缓冲区，只不过多提供">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/1590137301.jpg">
<meta property="article:published_time" content="2020-05-22T08:45:53.000Z">
<meta property="article:modified_time" content="2020-07-04T11:50:30.314Z">
<meta property="article:author" content="Chenyumeng">
<meta property="article:tag" content="笔记">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="NIO">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://ipvb.gitee.io/blog/assets/img/1590137301.jpg">

<link rel="canonical" href="https://ipvb.gitee.io/blog/2020/05/22/Java%20NIO%20Buffer/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>Java NIO Buffer | Chenyumeng的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <link rel="stylesheet" href="/dist/css/share.min.css">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chenyumeng的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">热爱自己，热爱生活</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">29</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">1</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">32</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="search-pop-overlay">
  <div class="popup search-popup">
      <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

  </div>
</div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/chen-yumeng" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://ipvb.gitee.io/blog/2020/05/22/Java%20NIO%20Buffer/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/touxiang.JPG">
      <meta itemprop="name" content="Chenyumeng">
      <meta itemprop="description" content="用来记录自己学习中所遇到的问题以及如何解决和自己所学知识的理解">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chenyumeng的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java NIO Buffer
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-05-22 16:45:53" itemprop="dateCreated datePublished" datetime="2020-05-22T16:45:53+08:00">2020-05-22</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-04 19:50:30" itemprop="dateModified" datetime="2020-07-04T19:50:30+08:00">2020-07-04</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/%E5%AD%A6%E4%B9%A0/" itemprop="url" rel="index"><span itemprop="name">学习</span></a>
                </span>
            </span>

          
            <span id="/blog/2020/05/22/Java%20NIO%20Buffer/" class="post-meta-item leancloud_visitors" data-flag-title="Java NIO Buffer" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>12k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>11 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="1-Java-NIO-Buffer"><a href="#1-Java-NIO-Buffer" class="headerlink" title="1. Java NIO Buffer"></a>1. <strong>Java NIO Buffer</strong></h3><p>Buffer是一个抽象类，位于java.nio包中，主要用作缓冲区。Buffer缓冲区本质上是一块可以写入数据，然后可以从中读取数据的内存。这块内存被包装成NIO Buffer对象，并提供了一组方法，用来方便的访问该块内存。</p>
<p>注意：Buffer是非线程安全类。</p>
<h4 id="1-1-Buffer类型的标记属性"><a href="#1-1-Buffer类型的标记属性" class="headerlink" title="1.1. Buffer类型的标记属性"></a>1.1. <strong>Buffer类型的标记属性</strong></h4><p>Buffer在内部也是利用byte[]作为内存缓冲区，只不过多提供了一些标记变量属性而已。当多线程访问的时候，可以清楚的知道当前数据的位置。</p>
<p>有三个重要的标记属性：capacity、position、limit。</p>
<p>除此之外，还有一个标记属性：mark，可以临时保持一个特定的position，需要的时候，可以恢复到这个位置。</p>
<a id="more"></a>

<h5 id="1-1-1-capacity"><a href="#1-1-1-capacity" class="headerlink" title="1.1.1. capacity"></a>1.1.1. capacity</h5><p>作为一个内存块，Buffer有一个固定的大小值，也叫“capacity”。你只能往里写capacity个数据。一旦Buffer满了，就不能再写入。</p>
<p>capacity与缓存的数据类型相关。指的不是内存的字节的数量，而是写入的对象的数量。比如使用的是一个保存double类型的Buffer（DoubleBuffer），写入的数据是double类型， 如果其 capacity 是100，那么我们最多可以写入100个 double 数据.</p>
<p>capacity一旦初始化，就不能不会改变。</p>
<p>原因是什么呢？</p>
<p>Buffer对象在初始化时，会按照capacity分配内部的内存。内存分配好后，大小就不能变了。分配内存时，一般使用Buffer的抽象子类ByteBuffer.allocate()方法，实际上是生成ByteArrayBuffer类。</p>
<h5 id="1-1-2-position"><a href="#1-1-2-position" class="headerlink" title="1.1.2. position"></a>1.1.2. position</h5><p>position表示当前的位置。position在Buffer的两种模式下的值是不同的。</p>
<p>读模式下的position的值为：</p>
<p>当读取数据时，也是从position位置开始读。当将Buffer从写模式切换到读模式，position会被重置为0。当从Buffer的position处读取数据时，position向前移动到下一个可读的位置。</p>
<p>写模式下的position的值为：</p>
<p>在写模式下，当写数据到Buffer中时，position表示当前的写入位置。初始的position值为0，position最大可为capacity – 1。</p>
<p>每当一个数据（byte、long等）写到Buffer后， position会向后移动到下一个可插入数据的可写的位置。</p>
<h5 id="1-1-3-limit"><a href="#1-1-3-limit" class="headerlink" title="1.1.3. limit"></a>1.1.3. limit</h5><p>limit表示最大的限制。在Buffer的两种模式下，limit的值是不同的。</p>
<p>读模式下的limit的值为：</p>
<p>读模式下，Buffer的limit表示最多能从Buffer里读多少数据。当Buffer从写切换到读模式时，limit的值，设置成写模式的position 值，也是是写模式下之前写入的数量值。</p>
<p>举一个简单的例子，说明一下读模式下的limit值：</p>
<p>先向Buffer写数据，Buffer在写模式。每写入一个数据，position向后面移动一个位置，值加一。假定写入了5个数，当写入完成后，position的值为5。这时，就可以读取数据了。当开始读取数据时，Buffer切换到读模式。limit的值，先会被设置成写入数据时的position值。这里是5，表示可以读取的最大限制是5个数。</p>
<p>写模式下的limit的值为：</p>
<p>limit表示表示可以写入的数据最大限制。在切换成写模式时，limit的值会被更改，设置成Buffer的capacity，为Buffer的容量。</p>
<h5 id="1-1-4-总结："><a href="#1-1-4-总结：" class="headerlink" title="1.1.4. 总结："></a>1.1.4. 总结：</h5><p>在Buffer的四个属性之间，有一个简单的数量关系，如下：</p>
<p>capacity&gt;=limit&gt;=position&gt;=mark&gt;=0</p>
<p>用一个表格，对着4个属性的进行一下对比：</p>
<table>
<thead>
<tr>
<th>属性</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>capacity</td>
<td>容量，即可以容纳的最大数据量；在缓冲区创建时被设定并且不能改变</td>
</tr>
<tr>
<td>limit</td>
<td>上界，缓冲区中当前数据量</td>
</tr>
<tr>
<td>position</td>
<td>位置，下一个要被读或写的元素的索引</td>
</tr>
<tr>
<td>mark（位置标记）</td>
<td>调用mark(pos)来设置mark=pos，再调用reset()可以让position恢复到标记的位置即position=mark</td>
</tr>
</tbody></table>
<h4 id="1-2-Buffer-类型"><a href="#1-2-Buffer-类型" class="headerlink" title="1.2. Buffer 类型"></a>1.2. <strong>Buffer 类型</strong></h4><p>在NIO中主要有八种缓冲区类，分别如下:</p>
<p>ByteBuffer</p>
<p>CharBuffer</p>
<p>DoubleBuffer</p>
<p>FloatBuffer</p>
<p>IntBuffer</p>
<p>LongBuffer</p>
<p>ShortBuffer</p>
<p>MappedByteBuffer</p>
<p><img src="/blog/assets/img/1590137301.jpg" alt="BUffer的主要子类"></p>
<p>这些 Buffer 覆盖了能从 IO 中传输的所有的 Java 基本数据类型。(其中MappedByteBuffer是专门用于内存映射的一种ByteBuffer)。</p>
<h4 id="1-3-Buffer中的方法"><a href="#1-3-Buffer中的方法" class="headerlink" title="1.3. Buffer中的方法"></a>1.3. <strong>Buffer中的方法</strong></h4><p>结合Buffer的几个方法，做了一个完整的实例，包含了从Buffer实例的获取、写入、读取、重复读、标记和重置等一个系列操作的完整流程。</p>
<h5 id="1-3-1-获取allocate（）方法"><a href="#1-3-1-获取allocate（）方法" class="headerlink" title="1.3.1. 获取allocate（）方法"></a>1.3.1. 获取allocate（）方法</h5><p>为了获取一个 Buffer 对象，我们首先需要分配内存空间。分配内存空间使用allocate()方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">allocateTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    byteBuffer = IntBuffer.allocate(<span class="number">20</span>);</span><br><span class="line">    System.out.println(<span class="string">"------------after allocateTest------------------"</span>);</span><br><span class="line">    System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">    System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">    System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里我们分配了20* sizeof(int)字节的内存空间.</p>
<p>输出的结果如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">------------after allocate------------------</span><br><span class="line">position=<span class="number">0</span></span><br><span class="line">limit=<span class="number">20</span></span><br><span class="line">capacity=<span class="number">20</span></span><br></pre></td></tr></table></figure>

<p>通过结果，可以看到Buffer属性的值。</p>
<h5 id="1-3-2-写put-方法"><a href="#1-3-2-写put-方法" class="headerlink" title="1.3.2. 写put()方法"></a>1.3.2. 写put()方法</h5><p>调用allocate分配内存后，buffer处于写模式。可以通过buffer的put方法写入数据。put方法有一个要求，需要写入的数据类型与Buffer的类型一致。</p>
<p>接着前面的例子，继续上写入的实例代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">putTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">        byteBuffer.put(i);</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(<span class="string">"------------after putTest------------------"</span>);</span><br><span class="line">    System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">    System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">    System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>写入5个元素后，输出的结果为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">------------after putTest------------------</span><br><span class="line">position=<span class="number">5</span></span><br><span class="line">limit=<span class="number">20</span></span><br><span class="line">capacity=<span class="number">20</span></span><br></pre></td></tr></table></figure>

<p>调用了put方法后，buffer处于写模式。写入5个数据后，可以看到，position 变成了5，指向了第6个可以写入的元素位置。</p>
<p>除了在新建的buffer之后，如何将buffer切换成写模式呢？</p>
<p>调用 Buffer.clear() 清空或 Buffer.compact()压缩方法，可以将 Buffer 转换为写模式。</p>
<h5 id="1-3-3-读切换flip-方法"><a href="#1-3-3-读切换flip-方法" class="headerlink" title="1.3.3. 读切换flip()方法"></a>1.3.3. 读切换flip()方法</h5><p>put方法写入数据之后，可以直接从buffer中读吗？</p>
<p>呵呵，不能。</p>
<p>还需要调用filp（）走一个转换的工作。flip()方法是Buffer的一个模式转变的重要方法。简单的说，是写模式翻转成读模式——写转读。</p>
<p>接着前面的例子，继续上flip（）方法的例子代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">flipTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    byteBuffer.flip();</span><br><span class="line">    System.out.println(<span class="string">"------------after flipTest ------------------"</span>);</span><br><span class="line">    System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">    System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">    System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接着上一步的写入，在调用flip之后，buffer的属性有一些奇妙的变化。</p>
<p>运行上面的程序，输出如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">------------after flipTest ------------------</span><br><span class="line">position=<span class="number">0</span></span><br><span class="line">limit=<span class="number">5</span></span><br><span class="line">capacity=<span class="number">20</span></span><br></pre></td></tr></table></figure>

<p>注意到没有，position从前一个小节的5，变成了0。而limit的保存了之前的position，从20变成5。</p>
<p>这是为什么呢？ 先看其源码，Buffer.flip()方法的源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> Buffer <span class="title">flip</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    limit = position;</span><br><span class="line">    position = <span class="number">0</span>;</span><br><span class="line">    mark = -<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>解释一下，flip()方法主要是从读模式切换成写模式，调整的规则是：</p>
<p>（1）首先设置可读的长度limit。将写模式下的Buffer中内容的最后位置position值变为读模式下的limit位置值，新的limit值作为读越界位置；</p>
<p>（2）其次设置读的起始位置。将当position值置为0，表示从0位置开始读。转换后重头开始读。</p>
<p>（3）如果之前有mark保存的标记位置，还要消除。因为那是写模式下的mark标记。</p>
<h5 id="1-3-4-读get-方法"><a href="#1-3-4-读get-方法" class="headerlink" title="1.3.4. 读get() 方法"></a>1.3.4. 读get() 方法</h5><p>get()读数据很简单，每次从postion的位置读取一个数据，并且进行相应的buffer属性的调整。</p>
<p>接着前面的例子，继续上读取buffer的例子代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">getTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"------------after &amp;getTest 2------------------"</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">2</span>; i++) &#123;</span><br><span class="line">        <span class="keyword">int</span> j = byteBuffer.get();</span><br><span class="line">        System.out.println(<span class="string">"j = "</span> + j);</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">    System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">    System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">    System.out.println(<span class="string">"------------after &amp;getTest 3------------------"</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">3</span>; i++) &#123;</span><br><span class="line">        <span class="keyword">int</span> j = byteBuffer.get();</span><br><span class="line">        System.out.println(<span class="string">"j = "</span> + j);</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">    System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">    System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>先读2个，再读3个，输出的Buffer属性值如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">------------after &amp;getTest <span class="number">2</span>------------------</span><br><span class="line">j = <span class="number">0</span></span><br><span class="line">j = <span class="number">1</span></span><br><span class="line">position=<span class="number">2</span></span><br><span class="line">limit=<span class="number">5</span></span><br><span class="line">capacity=<span class="number">20</span></span><br><span class="line">------------after &amp;getTest <span class="number">3</span>------------------</span><br><span class="line">j = <span class="number">2</span></span><br><span class="line">j = <span class="number">3</span></span><br><span class="line">j = <span class="number">4</span></span><br><span class="line">position=<span class="number">5</span></span><br><span class="line">limit=<span class="number">5</span></span><br><span class="line">capacity=<span class="number">20</span></span><br></pre></td></tr></table></figure>

<p>读完之后，缓存的position 值变成了一个没有数据的元素位置，和limit的值相等，已经不能在读了。</p>
<p>读完之后，是否可以直接写数据呢？</p>
<p>不能。一旦读取了所有的 Buffer 数据，那么我们必须清理 Buffer，让其重新可写，可以调用 Buffer.clear() 或 Buffer.compact()。</p>
<h5 id="1-3-5-倒带rewind-方法"><a href="#1-3-5-倒带rewind-方法" class="headerlink" title="1.3.5. 倒带rewind()方法"></a>1.3.5. 倒带rewind()方法</h5><p>已经读完的数据，需要再读一遍，可以直接使用get方法吗？</p>
<p>答案是，不能。怎么办呢？</p>
<p>使用rewind() 方法，可以进重复读的设置。rewind()也叫倒带，就像播放磁带一样，倒回去，重新播放。</p>
<p>接着前面的例子，继续上重复读的例子代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">rewindTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    byteBuffer.rewind();</span><br><span class="line">    System.out.println(<span class="string">"------------after rewindTest ------------------"</span>);</span><br><span class="line">    System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">    System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">    System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实例的结果如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">------------after flipTest ------------------</span><br><span class="line">position=<span class="number">0</span></span><br><span class="line">limit=<span class="number">5</span></span><br><span class="line">capacity=<span class="number">20</span></span><br></pre></td></tr></table></figure>

<p>flip()方法主要是调整Buffer的 position 属性，调整的规则是：</p>
<p>（1）position设回0，所以你可以重读Buffer中的所有数据；</p>
<p>（2）limit保持不变，数据量还是一样的，仍然表示能从Buffer中读取多少个元素。</p>
<p>Buffer.rewind()方法的源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> Buffer <span class="title">rewind</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    position = <span class="number">0</span>;</span><br><span class="line">    mark = -<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>看到了实现的源码应该就会清楚flip()的作用了。rewind()方法与flip()很相似，区别在于rewind()不会影响limit，而flip()会重设limit属性值。</p>
<h5 id="1-3-6-mark-和reset"><a href="#1-3-6-mark-和reset" class="headerlink" title="1.3.6. mark( )和reset( )"></a>1.3.6. mark( )和reset( )</h5><p>Buffer.mark()方法将当前的 position 的值保存起来，放在mark属性中，让mark属性记住当前位置，之后可以调用Buffer.reset()方法将 position 的值恢复回来。</p>
<p>Buffer.mark()和Buffer.reset()方法是一一配套使用的。都是需要操作mark属性。</p>
<p>在重复读的实例代码中，读到第3个元素，使用mark（）方法，设置一下mark 属性，保存为第3个元素的位置。</p>
<p>下面上实例，演示一下mark和reset的结合使用。</p>
<p>实例继续接着上面的rewind倒带后的buffer 状态，开始reRead重复读，实例代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">reReadTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"------------after reReadTest------------------"</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">        <span class="keyword">int</span> j = byteBuffer.get();</span><br><span class="line">        System.out.println(<span class="string">"j = "</span> + j);</span><br><span class="line">        <span class="keyword">if</span> (i == <span class="number">2</span>) &#123;</span><br><span class="line">            System.out.println(<span class="string">"当 j = "</span> + i + <span class="string">" 时 position = 3, 调用 byteBuffer.mark()"</span>);</span><br><span class="line">            byteBuffer.mark();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">    System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">    System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后接着上一段reset（）实例代码，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">resetTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"------------after resetTest------------------"</span>);</span><br><span class="line">    byteBuffer.reset();</span><br><span class="line">    System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">    System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">    System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面我们在position 3时调用 mark() 方法将当前的 position 保存起来(在读模式，因此保存的是读的 position。接着使用 reset() 恢复原来的读 position，因此读 position 就为3，可以再次开始从第2个元素读取数据.</p>
<p>输出的结果是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">------------after reReadTest------------------</span><br><span class="line">j = <span class="number">0</span></span><br><span class="line">j = <span class="number">1</span></span><br><span class="line">j = <span class="number">2</span></span><br><span class="line">当 j = <span class="number">2</span> 时 position = <span class="number">3</span>, 调用 byteBuffer.mark()</span><br><span class="line">j = <span class="number">3</span></span><br><span class="line">j = <span class="number">4</span></span><br><span class="line">position=<span class="number">5</span></span><br><span class="line">limit=<span class="number">5</span></span><br><span class="line">capacity=<span class="number">20</span></span><br><span class="line">------------after resetTest------------------</span><br><span class="line">position=<span class="number">3</span></span><br><span class="line">limit=<span class="number">5</span></span><br><span class="line">capacity=<span class="number">20</span></span><br></pre></td></tr></table></figure>

<p>调用reset之后，position的值为3，表示可以从第三个元素开始读。</p>
<p>Buffer.mark()和Buffer.reset()其实很简答，其源码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> Buffer <span class="title">mark</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    mark = position;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> Buffer <span class="title">reset</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> m = mark;</span><br><span class="line">        <span class="keyword">if</span> (m &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> InvalidMarkException();</span><br><span class="line">        position = m;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h5 id="1-3-7-clear（）清空"><a href="#1-3-7-clear（）清空" class="headerlink" title="1.3.7. clear（）清空"></a>1.3.7. clear（）清空</h5><p>clear（）方法的作用有两种：</p>
<p>（1）写模式下，当一个 buffer 已经写满数据时，调用 clear（）方法，切换成读模式，可以从头读取 buffer 的数据；</p>
<p>（2）读模式下，调用 clear（）方法，将buffer切换为写模式，将postion为清零，limit设置为capacity最大容量值，可以一直写入，直到buffer写满。</p>
<p>接着上面的实例，使用实例代码，演示一下clear方法。</p>
<p>代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">clearTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"------------after clearTest------------------"</span>);</span><br><span class="line">    byteBuffer.clear();</span><br><span class="line">    System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">    System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">    System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行之后，结果如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">------------after clear------------------</span><br><span class="line">position=<span class="number">0</span></span><br><span class="line">limit=<span class="number">20</span></span><br><span class="line">capacity=<span class="number">20</span></span><br></pre></td></tr></table></figure>

<p>在clear（）之前，buffer是在读模式下。clear（）之后，可以看到，清空了position 的值，设置为起始位置。</p>
<p>clear 方法源码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> Buffer <span class="title">clear</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    position = <span class="number">0</span>;</span><br><span class="line">    limit = capacity;</span><br><span class="line">    mark = -<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>根据源码我们可以知道，clear 将 positin 设置为0，将 limit 设置为 capacity。</p>
<h4 id="1-4-Buffer-的使用"><a href="#1-4-Buffer-的使用" class="headerlink" title="1.4. Buffer 的使用"></a>1.4. <strong>Buffer 的使用</strong></h4><h5 id="1-4-1-使用的基本步骤"><a href="#1-4-1-使用的基本步骤" class="headerlink" title="1.4.1. 使用的基本步骤"></a>1.4.1. 使用的基本步骤</h5><p>总结一下，使用 NIO Buffer 的步骤如下:</p>
<p>一：将数据写入到 Buffer 中；</p>
<p>二：调用 Buffer.flip()方法，将 NIO Buffer 转换为读模式；</p>
<p>三：从 Buffer 中读取数据；</p>
<p>四：调用 Buffer.clear() 或 Buffer.compact()方法，将 Buffer 转换为写模式。</p>
<p>当我们将数据写入到 Buffer 中时，Buffer 会记录我们已经写了多少的数据；当我们需要从 Buffer 中读取数据时，必须调用 Buffer.flip()将 Buffer 切换为读模式。</p>
<h5 id="1-4-2-完整的实例代码"><a href="#1-4-2-完整的实例代码" class="headerlink" title="1.4.2. 完整的实例代码"></a>1.4.2. 完整的实例代码</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.cg.test.NIO;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.nio.IntBuffer;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@program</span>: JavaSourceLearm-&gt;TestNIOBuffer</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>:</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: cg</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@create</span>: 2020-05-22 16:34</span></span><br><span class="line"><span class="comment"> **/</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestNIOBuffer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> IntBuffer byteBuffer = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"分配内存"</span>);</span><br><span class="line">        allocateTest();</span><br><span class="line">        System.out.println(<span class="string">"写入"</span>);</span><br><span class="line">        putTest();</span><br><span class="line">        System.out.println(<span class="string">"翻转"</span>);</span><br><span class="line">        flipTest();</span><br><span class="line">        System.out.println(<span class="string">"读取"</span>);</span><br><span class="line">        getTest();</span><br><span class="line">        System.out.println(<span class="string">"重复读"</span>);</span><br><span class="line">        rewindTest();</span><br><span class="line">        reReadTest();</span><br><span class="line">        System.out.println(<span class="string">"make&amp;reset写读"</span>);</span><br><span class="line">        resetTest();</span><br><span class="line">        System.out.println(<span class="string">"清空"</span>);</span><br><span class="line">        clearTest();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">allocateTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        byteBuffer = IntBuffer.allocate(<span class="number">20</span>);</span><br><span class="line">        System.out.println(<span class="string">"------------after allocateTest------------------"</span>);</span><br><span class="line">        System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">        System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">        System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">putTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">            byteBuffer.put(i);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"------------after putTest------------------"</span>);</span><br><span class="line">        System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">        System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">        System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">flipTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        byteBuffer.flip();</span><br><span class="line">        System.out.println(<span class="string">"------------after flipTest ------------------"</span>);</span><br><span class="line">        System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">        System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">        System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">rewindTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        byteBuffer.rewind();</span><br><span class="line">        System.out.println(<span class="string">"------------after rewindTest ------------------"</span>);</span><br><span class="line">        System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">        System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">        System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">getTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"------------after &amp;getTest 2------------------"</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">2</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">int</span> j = byteBuffer.get();</span><br><span class="line">            System.out.println(<span class="string">"j = "</span> + j);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">        System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">        System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">        System.out.println(<span class="string">"------------after &amp;getTest 3------------------"</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">3</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">int</span> j = byteBuffer.get();</span><br><span class="line">            System.out.println(<span class="string">"j = "</span> + j);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">        System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">        System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">reReadTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"------------after reReadTest------------------"</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">int</span> j = byteBuffer.get();</span><br><span class="line">            System.out.println(<span class="string">"j = "</span> + j);</span><br><span class="line">            <span class="keyword">if</span> (i == <span class="number">2</span>) &#123;</span><br><span class="line">                System.out.println(<span class="string">"当 j = "</span> + i + <span class="string">" 时 position = 3, 调用 byteBuffer.mark()"</span>);</span><br><span class="line">                byteBuffer.mark();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">        System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">        System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">resetTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"------------after resetTest------------------"</span>);</span><br><span class="line">        byteBuffer.reset();</span><br><span class="line">        System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">        System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">        System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">clearTest</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"------------after clearTest------------------"</span>);</span><br><span class="line">        byteBuffer.clear();</span><br><span class="line">        System.out.println(<span class="string">"position="</span> + byteBuffer.position());</span><br><span class="line">        System.out.println(<span class="string">"limit="</span> + byteBuffer.limit());</span><br><span class="line">        System.out.println(<span class="string">"capacity="</span> + byteBuffer.capacity());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>学习于<a href="https://www.cnblogs.com/crazymakercircle/p/9826798.html" target="_blank" rel="noopener">疯狂创客圈</a></p>

    </div>

    
    
    

    
    <div>    
      
        <ul class="post-copyright">
          <li class="post-copyright-link">
          <strong>本文作者：</strong>
          <a href="/" title="欢迎访问 Chenyumeng 的个人博客">Chenyumeng</a>
          </li>

          <li class="post-copyright-link">
            <strong>本文标题：</strong>
            <a href="https://ipvb.gitee.io/blog/2020/05/22/Java%20NIO%20Buffer/" title="Java NIO Buffer">Java NIO Buffer</a>
          </li>

          <li class="post-copyright-link">
            <strong>本文链接：</strong>
            <a href="https://ipvb.gitee.io/blog/2020/05/22/Java%20NIO%20Buffer/" title="Java NIO Buffer">https://ipvb.gitee.io/blog/2020/05/22/Java%20NIO%20Buffer/</a>
          </li>

          <li class="post-copyright-date">
            <strong>发布时间： </strong>2020年5月22日 - 16时05分
          </li>  

          <li class="post-copyright-license">
            <strong>版权声明： </strong>
            本文由 Chenyumeng 原创。
          </li>
        </ul>
      
    </div>
      
  <div class="popular-posts-header">相关文章推荐</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\05\23\Java NIO Channel\" rel="bookmark">Java NIO Channel</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\05\23\Java NIO Selector\" rel="bookmark">Java NIO Selector</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\16\linux JDK安装\" rel="bookmark">linux JDK安装</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\15\ZooKeeper\" rel="bookmark">ZooKeeper单机与集群安装笔记</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\15\centOs7_Redis\" rel="bookmark">centOs7下安装Redis记录</a></div>
    </li>
  </ul>

        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blog/images/wechatpay.png" alt="Chenyumeng 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blog/images/alipay.png" alt="Chenyumeng 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <div>
        
          <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------　　　　本文结束　<i class="fa fa-heart"></i>　感谢您的阅读　　　　-------------</div>
    
</div>
        
      </div>

      <footer class="post-footer">
          
          <div class="post-tags">
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2020/05/06/2020%E5%B9%B405%E6%9C%8806%E6%97%A5/" rel="prev" title="2020年05月06日软件设计师每日一练">
      <i class="fa fa-chevron-left"></i> 2020年05月06日软件设计师每日一练
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2020/05/23/Java%20NIO%20Channel/" rel="next" title="Java NIO Channel">
      Java NIO Channel <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

    <!-- 引入share.js -->
    
      <div data-weibo-title="分享到微博" data-qq-title="分享到QQ" data-douban-title="分享到豆瓣" class="social-share" class="share-component" data-disabled="twitter,facebook" data-description="Share.js - 一键分享到微博，QQ空间，腾讯微博，人人，豆瓣">分享到：</div>
    
  </div>


          </div>
          
    
  <div class="comments">
    <div id="lv-container" data-id="city" data-uid="MTAyMC80OTExNy8yNTYxMg=="></div>
  </div>
  

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-Java-NIO-Buffer"><span class="nav-number">1.</span> <span class="nav-text">1. Java NIO Buffer</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-Buffer类型的标记属性"><span class="nav-number">1.1.</span> <span class="nav-text">1.1. Buffer类型的标记属性</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-1-1-capacity"><span class="nav-number">1.1.1.</span> <span class="nav-text">1.1.1. capacity</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-1-2-position"><span class="nav-number">1.1.2.</span> <span class="nav-text">1.1.2. position</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-1-3-limit"><span class="nav-number">1.1.3.</span> <span class="nav-text">1.1.3. limit</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-1-4-总结："><span class="nav-number">1.1.4.</span> <span class="nav-text">1.1.4. 总结：</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-Buffer-类型"><span class="nav-number">1.2.</span> <span class="nav-text">1.2. Buffer 类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-Buffer中的方法"><span class="nav-number">1.3.</span> <span class="nav-text">1.3. Buffer中的方法</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-3-1-获取allocate（）方法"><span class="nav-number">1.3.1.</span> <span class="nav-text">1.3.1. 获取allocate（）方法</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-3-2-写put-方法"><span class="nav-number">1.3.2.</span> <span class="nav-text">1.3.2. 写put()方法</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-3-3-读切换flip-方法"><span class="nav-number">1.3.3.</span> <span class="nav-text">1.3.3. 读切换flip()方法</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-3-4-读get-方法"><span class="nav-number">1.3.4.</span> <span class="nav-text">1.3.4. 读get() 方法</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-3-5-倒带rewind-方法"><span class="nav-number">1.3.5.</span> <span class="nav-text">1.3.5. 倒带rewind()方法</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-3-6-mark-和reset"><span class="nav-number">1.3.6.</span> <span class="nav-text">1.3.6. mark( )和reset( )</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-3-7-clear（）清空"><span class="nav-number">1.3.7.</span> <span class="nav-text">1.3.7. clear（）清空</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-4-Buffer-的使用"><span class="nav-number">1.4.</span> <span class="nav-text">1.4. Buffer 的使用</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-4-1-使用的基本步骤"><span class="nav-number">1.4.1.</span> <span class="nav-text">1.4.1. 使用的基本步骤</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-4-2-完整的实例代码"><span class="nav-number">1.4.2.</span> <span class="nav-text">1.4.2. 完整的实例代码</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Chenyumeng"
      src="/blog/images/touxiang.JPG">
  <p class="site-author-name" itemprop="name">Chenyumeng</p>
  <div class="site-description" itemprop="description">用来记录自己学习中所遇到的问题以及如何解决和自己所学知识的理解</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">32</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">29</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/chen-yumeng" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;chen-yumeng" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/3123221441" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;3123221441" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://github.com/" title="https:&#x2F;&#x2F;github.com&#x2F;" rel="noopener" target="_blank">Github</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chenyumeng</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">390k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">5:55</span>
</div>

        






  <script>
  function leancloudSelector(url) {
    url = encodeURI(url);
    return document.getElementById(url).querySelector('.leancloud-visitors-count');
  }
  if (CONFIG.page.isPost) {
    function addCount(Counter) {
      var visitors = document.querySelector('.leancloud_visitors');
      var url = decodeURI(visitors.id);
      var title = visitors.dataset.flagTitle;

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url })))
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length > 0) {
            var counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
            Counter('put', '/classes/Counter/' + counter.objectId, { time: { '__op': 'Increment', 'amount': 1 } })
              .then(response => response.json())
              .catch(error => {
                console.error('Failed to save visitor count', error);
              })
          } else {
              Counter('post', '/classes/Counter', { title, url, time: 1 })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  } else {
    function showTime(Counter) {
      var visitors = document.querySelectorAll('.leancloud_visitors');
      var entries = [...visitors].map(element => {
        return decodeURI(element.id);
      });

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url: { '$in': entries } })))
        .then(response => response.json())
        .then(({ results }) => {
          for (let url of entries) {
            let target = results.find(item => item.url === url);
            leancloudSelector(url).innerText = target ? target.time : 0;
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  }

  fetch('https://app-router.leancloud.cn/2/route?appId=')
    .then(response => response.json())
    .then(({ api_server }) => {
      var Counter = (method, url, data) => {
        return fetch(`https://${api_server}/1.1${url}`, {
          method,
          headers: {
            'X-LC-Id'     : '',
            'X-LC-Key'    : '',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      if (CONFIG.page.isPost) {
        if (CONFIG.hostname !== location.hostname) return;
        addCount(Counter);
      } else if (document.querySelectorAll('.post-title-link').length >= 1) {
        showTime(Counter);
      }
    });
  </script>


      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

<script>
NexT.utils.loadComments(document.querySelector('#lv-container'), () => {
  window.livereOptions = {
    refer: location.pathname.replace(CONFIG.root, '').replace('index.html', '')
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
});
</script>

  <script src="/dist/js/social-share.min.js"></script>
</body>
</html>
